<template>
	<view>
		<uni-forms ref="form" :value="formData">
			<uni-forms-item name="phone">
				<uni-easyinput type="text" v-model="formData.phone" placeholder="请输入用户名(手机号)" maxlength="11" />
			</uni-forms-item>
			<uni-forms-item name="password">
				<uni-easyinput type="password" v-model="formData.password" placeholder="请输入密码" maxlength="15" />
			</uni-forms-item>
		</uni-forms>
		<view class="btns">
			<button @click="submitForm">立即登录</button>
			<button @click="register" type="info">注册</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				formData: {
					phone: '',
					password: ''
				},
				formRules: {
					phone: {
						rules: [{
								required: true,
								errorMessage: '手机号不能为空'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									let iphoneReg = (
										/^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/
									); //手机号码
									if (!iphoneReg.test(value)) {
										callback('请输入正确的手机号')
									}
									return true
								}
							}
						],
					},
					password: {
						rules: [{
							required: true,
							errorMessage: '密码不能为空'
						}, {
							validateFunction: function(rule, value, data, callback) {
								if (value.length > 15 || value.length < 8) {
									callback('密码长度在8-15位')
								} else {
									return true
								}
							}
						}]
					},
				}
			}
		},
		onReady() {
			this.$refs.form.setRules(this.formRules);
		},
		methods: {
			register() { //注册
				uni.navigateTo({
					url: '/pages/Mine/Register',
				});

			},
			submitForm() { //登录
				var that = this;
				this.$refs.form.validate().then(async (data) => {
						console.log('表单数据信息：', data);
						const {data:res} = await that.$myRequest({
							url: '/loginBefore/login',
							method: 'POST',
							data: {
								phone: that.formData.phone,
								password: that.formData.password
							},
						})
						console.log(res);
						if (res.code == 20000) { //成功
							// 存储token到storage
							uni.setStorageSync("token", res.data.token)
							uni.showToast({
								title: '登录成功',
								icon: 'success',
								success() {
									// 跳转上页面
									setTimeout(function() {
										uni.switchTab({
											url:'/pages/Index'
										})
									}, 1000);
								}
							})
						}

					})
					.catch(err => {
						console.log('表单错误信息：', err);
						return false
					})



			},

		}
	}
</script>

<style lang="scss">
	page {
		background-color: #fff;
	}
</style>
<style lang="scss" scoped>
	/deep/.uni-forms-item:first-child {
		margin-top: 50rpx;
	}

	/deep/.uni-easyinput {
		width: 90%;
		margin: 10rpx auto;
	}

	/deep/.uni-forms-item__error {
		margin-left: 40rpx;
	}

	button {
		width: 80%;
		margin: 20rpx auto;

		&:first-child {
			background-color: #d81e06;
			color: #fff;
		}
	}
	.register {
		display: flex;
		justify-content: center;
		color: #d81e06;
	}
</style>
